<template>
  <!-- 新增活动 -->
  <el-dialog
    v-model="visible"
    :title="
      form.shopDiscountId
        ? visitDetail
          ? '查看折扣活动'
          : '修改折扣活动'
        : '新增折扣活动'
    "
    class="addGroupBuy"
    width="700px"
    center
    top="10vh"
    :close-on-click-modal="false"
    @closed="close"
  >
    <div class="addGroupBuyBox">
      <el-form
        ref="formRef"
        class="formBox"
        :model="form"
        label-width="150px"
        :rules="rules"
        :disabled="visitDetail"
      >
        <el-form-item label="活动名称" prop="discountName">
          <el-input
            v-model="form.discountName"
            maxlength="15"
            placeholder="请输入活动名称"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            maxlength="200"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="活动时间" prop="discountDate">
          <el-date-picker
            v-model="dateInfo"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="商品限购" prop="ifLimit">
          <el-radio-group v-model="form.ifLimit" class="comRadio">
            <el-radio :label="1">不限购</el-radio>
            <el-radio :label="2">限购</el-radio>
          </el-radio-group>
          <el-input
            v-model="form.limitNumber"
            maxlength="9"
            :disabled="form.ifLimit === 1"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px"
          />&nbsp;件/人
        </el-form-item>
        <el-form-item label="活动商品限量" prop="ifNumber">
          <el-radio-group v-model="form.ifNumber" class="comRadio">
            <el-radio :label="0">不限量</el-radio>
            <el-radio :label="1">限量</el-radio>
          </el-radio-group>
          <el-input
            v-model="form.number"
            maxlength="9"
            :disabled="form.ifNumber === 0"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px"
          />&nbsp;件
        </el-form-item>
        <el-form-item label="活动预热" prop="ifEnable">
          <el-radio-group v-model="form.ifEnable" class="comRadio">
            <el-radio :label="1">停用</el-radio>
            <el-radio :label="2">启用</el-radio>
          </el-radio-group>
          <el-input
            v-model="form.enableTime"
            maxlength="9"
            :disabled="form.ifEnable === 1"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px"
          />&nbsp;小时前
        </el-form-item>
        <el-form-item label="优惠券叠加" prop="ifAdd">
          <el-radio-group v-model="form.ifAdd" class="comRadio">
            <el-radio :label="1">叠加</el-radio>
            <el-radio :label="0">不叠加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="applyType" label="活动商品" prop="commodity">
          <span
            class="selectBtn"
            @click="chooseProduct"
          ><span v-if="!visitDetail">请选择</span><span v-else>查看商品</span><i v-if="form.details.length !== 0" class="selectNum">{{
            form.details.length
          }}</i></span>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button
        v-show="!visitDetail"
        type="primary"
        @click="addSeckillFn"
      >保 存</el-button>
      <el-button
        v-if="visitDetail"
        type="primary"
        @click="goToDiscount"
      >取 消</el-button>
      <el-button v-else type="danger" @click="goToDiscount">取 消</el-button>
    </span>
    <ProductSelectVue
      ref="productSelectRef"
      :status="visitDetail ? 0 : 1"
      @selected="setProducts"
    />
  </el-dialog>
</template>

<script setup>
import { defineComponent, ref } from 'vue';
import ProductSelectVue from './productSelect.vue';
import {
  addDiscount,
  discountUpdate,
  getDiscountDetail,
} from '@/api/marketing';

defineComponent({
  name: 'DiscountForm',
});

function initForm (data) {
  return {
    shopDiscountId: (data && data.shopDiscountId) || null,
    discountName: (data && data.discountName) || '', // 折扣活动名称
    remark: (data && data.remark) || '', // 备注
    details: (data && data.details) || [], // 商品明细数据
    enableTime: (data && data.enableTime) || null, // 预热几小时前
    endTime: (data && data.endTime) || '', // 折扣活动结束时间
    ifEnable: (data && data.ifEnable) || 1, // 秒杀活动预热 1-停用 2-启用
    ifLimit: (data && data.ifLimit) || 1, // 商品限购 1-不限购 2-限购
    limitNumber: (data && data.limitNumber) || null, // 限购几件/人
    ifNumber: (data && data.ifNumber) || 0, // 是否限量
    number: (data && data.number) || null, // 限制数量
    ifAdd: (data && data.ifAdd) || 1, // 优惠券是否叠加 1-是 0-否
    startTime: (data && data.startTime) || '', // 活动开始时间
    effectiveTime: (data && data.effectiveTime) || null,
    person: (data && data.person) || null,
  };
}
const visitDetail = ref(false);
const visible = ref(false);
const formRef = ref();
const form = ref(initForm());
const inputDiscountTableData = ref([]);
const multipleTableRef = ref();
const dateInfo = ref([]);
const groupQuery = ref({
  activityId: null,
  page: 1,
  pageSize: 10,
});
const rules = {
  discountName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
  ],
  discountDate: [
    { required: true, validator: validDate, trigger: 'change' },
  ],
  ifLimit: [
    { validator: validLimit, trigger: 'change' },
  ],
  ifNumber: [
    { validator: validNumber, trigger: 'change' },
  ],
  ifEnable: [
    { validator: validEnable, trigger: 'change' },
  ],
  commodity: [
    { required: true, validator: validCommodity, trigger: 'change' },
  ]
};

function validDate (rule, value, callback) {
  if (!dateInfo.value || !dateInfo.value.length) {
    return callback(new Error('请选择活动时间'))
  }
  callback()
}

function validLimit (rule, value, callback) {
  if (form.value.ifLimit === 2 && !form.value.limitNumber) {
    return callback(new Error('请填写商品限购数量'))
  }
  callback()
}
function validNumber (rule, value, callback) {
  if (form.value.ifNumber === 1 && !form.value.number) {
    return callback(new Error('请选择活动商品数量'))
  }
  callback()
}
function validEnable (rule, value, callback) {
  if (form.value.ifEnable === 2 && !form.value.enableTime) {
    return callback(new Error('请填写活动预热时间'))
  }
  callback()
}
function validCommodity (rule, value, callback) {
  if (!form.value.details || !form.value.details.length) {
    return callback(new Error('请选择活动商品'))
  }
  callback()
}
function vildateForm (str) {
  if (str) {
    formRef.value.validateField(str)
  }
}

const emit = defineEmits(['reset']);
defineExpose({
  open,
  close,
});

function open (id, isDetail) {
  form.value.shopDiscountId = id;
  visitDetail.value = isDetail;
  if (id) {
    getDiscountInfo();
  }
  visible.value = true;
}
function close () {
  visible.value = false;
  form.value = initForm();
  groupQuery.value.page = 1;
  dateInfo.value = [];
  inputDiscountTableData.value = [];
  multipleTableRef.value?.clearSelection();
  formRef.value?.resetFields();
}

function addSeckillFn () {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.value.ifLimit === 2 && form.value.limitNumber === null) {
        ElMessage.warning('请填写活动限购多少件');
        return false;
      }
      if (form.value.ifNumber === 2 && form.value.number === null) {
        ElMessage.warning('请输入活动限制数量');
        return false;
      }
      if (form.value.ifEnable === 2 && form.value.enableTime === null) {
        ElMessage.warning('请填写活动预热前多少小时');
        return false;
      }
      form.value.startTime = dateInfo.value[0];
      form.value.endTime = dateInfo.value[1];
      const fn = form.value.shopDiscountId ? discountUpdate : addDiscount
      fn(form.value).then((res) => {
        if (res.code === '') {
          ElMessage.success('修改成功');
          dateInfo.value = [];
          form.value = initForm();
          emit('reset');
        }
      });
    } else {
      return false;
    }
  });
}

/**
 * 商品选择模块
 */
const productSelectRef = ref();
function chooseProduct () {
  productSelectRef.value.show({
    id: form.value.shopDiscountId,
  });
}

// 编辑时表格默认勾选
// setRowSelection(){
//   if (multipleTableRef.value) {
//     for (let i = 0; i < groupData.value.length; i++) {
//       for (let j = 0; j < form.value.details.length; j++) {
//         if (groupData.value[i].productId === form.value.details[j].productId && groupData.value[i].skuId === form.value.details[j].skuId) {
//           multipleTableRef.value.toggleRowSelection(groupData.value[i]);
//           console.log('执行了')
//         }
//       }
//     }
//   }
// },
// 保存选择商品ID
function setProducts (list) {
  form.value.details = list
  vildateForm('commodity');
}
// 跳转折扣列表
function goToDiscount () {
  emit('reset');
}
function getDiscountInfo () {
  form.value.details = [];
  getDiscountDetail({
    shopDiscountId: form.value.shopDiscountId,
  }).then((res) => {
    form.value = initForm(res.data);
    const idList = res.data.products;
    idList.forEach((i) => {
      form.value.details.push({
        discount: i.discount,
        price: i.discountPrice,
        productId: i.productId,
        skuId: i.skuId,
      });
    });
    dateInfo.value = [form.value.startTime, form.value.endTime];
  });
}
</script>

<style lang="scss" scoped>
.addGroupBuy {
  background: #ffffff;
  .dialog-footer {
    display: flex;
    justify-content: center;
    .el-button {
      margin: 0px 16px;
    }
  }
  .formBox {
    margin-top: 20px;
    .comRadio {
      width: 200px;
      display: flex;
      .el-radio {
        flex: 1;
        margin: 0;
      }
    }
    .applyType {
      span {
        width: 100px;
        height: 30px;
        line-height: 30px;
        background: #66b1ff;
        color: #ffffff;
        text-align: center;
        display: inline-block;
        font-size: 14px;
        margin-right: 30px;
        border-radius: 4px;
        cursor: pointer;
        position: relative;
        i {
          position: absolute;
          right: -10px;
          top: -10px;
          width: 25px;
          height: 25px;
          line-height: 25px;
          background: #ffffff;
          border-radius: 50%;
          border: 1px solid #66b1ff;
          text-align: center;
          color: #3a68f2;
          font-style: normal;
          font-size: 12px;
        }
      }
    }
  }
  .footBtnBox {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>